# 输出分隔符和开始消息
Write-Output "===================================================="
Write-Output "deploy backend start"

# 获取脚本所在的目录
$SCRIPT_DIR = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
Set-Location -Path $SCRIPT_DIR

# 定义变量
$ROOT_DIR = Split-Path -Path (Split-Path -Path $SCRIPT_DIR -Parent) -Parent
$PLUGIN_DIR = Join-Path $ROOT_DIR "plugins"
$BACKEND_DIR = Join-Path $ROOT_DIR "wex-backend"

# 整合扩展到项目中
Write-Output "start add plugins..."
$plugin_dirs = Get-ChildItem -Directory $PLUGIN_DIR

foreach ($plugin_dir in $plugin_dirs) {
    $backend_dir = Join-Path $plugin_dir.FullName "backend"
    if (Test-Path -Path $backend_dir) {
        $plugin_name = $plugin_dir.Name
        $target_dir = Join-Path $BACKEND_DIR "plugin/plugins/$plugin_name"
        if (-Not (Test-Path -Path $target_dir)) {
            New-Item -ItemType Directory -Path $target_dir
        }
        Copy-Item -Path "$backend_dir\*" -Destination $target_dir -Recurse
        Write-Output "Moved plugin $plugin_name to $target_dir"
    }
}
Write-Output "add plugins done"

Write-Output "Deploy backend server..."
Set-Location -Path $BACKEND_DIR

Copy-Item -Path "$SCRIPT_DIR\env.py" -Destination "$BACKEND_DIR\wex\env.py" -Recurse

# 安装依赖
pip install -r requirements.txt

# 执行数据库迁移和其他 Django 命令
python manage.py migrate
python manage.py init_system

# 重新加载 pm2 服务
pm2 reload ecosystem.config.js

# 记录部署
python manage.py deploy_record

Write-Output "Done"
Write-Output "deploy backend end"
Write-Output "===================================================="
